package org.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Auther: qingle
 * @Date: 2024/9/8-6:21
 * @Description: Http Utils
 * @version: 1.0
 */
public class HttpUtils {

	/**
	 * 获取文件大小
	 * @param url
	 * @return
	 * @throws IOException
	 */
  public static long getHttpFileContentLength(String url) throws IOException {
		int contentLength;
	  HttpURLConnection httpURLConnection = null;
	  try {
			httpURLConnection = getHttpURLConnection(url);
		  contentLength = httpURLConnection.getContentLength();
	  } finally {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
	  }
		return contentLength;
  }

	/**
	 * 分块下载
	 * @param url
	 * @param startPos
	 * @param endPos
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection getHttpURLConnection(String url, long startPos, long endPos) throws IOException {
		HttpURLConnection httpURLConnection = getHttpURLConnection(url);
		LogUtils.info("开始下载分块：{} --> {}", startPos, endPos);
		if (endPos != 0) {
			httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
		}else {
			httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "-");
		}
		return httpURLConnection;
	}


	public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
		URL url1 = new URL(url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url1.openConnection();
		// 想文件所在的服务器发送标识信息
		httpURLConnection
			.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36");
		return httpURLConnection;
	}

	public static String getHttpFileName(String url) throws IOException {
		int index = url.lastIndexOf("/");
		return url.substring(index + 1);
	}

}
